const express = require('express')
const router = express.Router();
const multer = require('multer')
const fs = require('fs')
const path = require('path')

var upload = multer({
    dest: path.join(__dirname,'./../uploads')
});//定义图片上传的临时目录

//返回上传页面
router.get('/',(req,res,next)=>{
    res.setHeader('Content-Type', 'text/html');
    res.sendFile(path.join(__dirname,'../views/upload.html'));
});
router.get('/bootstrap',(req,res,next)=>{
    // res.setHeader('Content-Type', 'text/html');
    res.sendFile(path.join(__dirname,'../node_modules/bootstrap/dist/css/bootstrap.css'));
});

// 单域单文件上传：input[file]的 multiple != "multiple"
router.post('/upload', upload.single('file'), function(req, res, next) {
    // req.file 是 前端表单name=="imageFile" 的文件信息（不是数组）
    // console.log(req.file);
    const jsonFilePath = path.join(__dirname,'../uploads/upload_img.json');
    const upPath = Date.now().toString()+'_'+req.file.originalname;
    fs.rename(req.file.path, path.join(__dirname,'./../uploads/'+upPath), function(err) {
        if (err) {
            throw err;
        }
        console.log('上传成功!');
        var results=JSON.parse(fs.readFileSync(jsonFilePath));
        results.filename.push(upPath);
        fs.writeFileSync(jsonFilePath,JSON.stringify(results));

    })

    res.writeHead(200, {
        "Access-Control-Allow-Origin": "*"
    });
    res.end(JSON.stringify(req.file)+JSON.stringify(req.body));
})

//返回图片list
router.get('/getimglist',(req,res,next)=>{
    var result = fs.readFileSync(path.join(__dirname,'../uploads/upload_img.json'));
    res.writeHead(200, {
        "Access-Control-Allow-Origin": "*"
    });
    res.end(result.toString());
})


//返回图片
router.get('/imgs/:id',(req,res,next)=>{
    let imgId = req.params.id;
    res.sendFile(path.join(__dirname,'./../uploads/'+imgId));
})

module.exports = router;
